package com.ydj;

import java.nio.channels.FileChannel
import java.nio.channels.FileLock

import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.SpringApplication
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.test.context.ActiveProfiles

import com.ydj.constants.PingPongConstant
import com.ydj.entity.PingPongEntity

import cn.hutool.http.HttpRequest
import cn.hutool.http.HttpResponse
import cn.hutool.http.HttpStatus
import spock.lang.Shared
import spock.lang.Specification

@SpringBootTest
@ActiveProfiles("test")
class PingComponentTest extends Specification {
    @Autowired
    PingComponent pingComponent;
    
    @Test
    def "pong server started. ping server send message with already locked 1"() {
        given: "set lockIndex=1"
            pingComponent.setLockIndex(1);
            PingPongEntity entity = pingComponent.sendPing();
        expect:
            entity.getStatus()==PingPongConstant.STATUS_RESP_OK;
            System.out.println(entity.getStatus());
    }
    
    @Test
    def "pong server started. ping server send message with already locked 2"() {
        given: "set lockIndex=2"
            pingComponent.setLockIndex(2);
            PingPongEntity entity = pingComponent.sendPing();
        expect:
            entity.getStatus()==PingPongConstant.STATUS_RATE_LIMITED;
    }
    
    @Test
    def "pong server started. send 3 message"() {
        given: ""
             Integer result2=null;
             for(int i=0;i<3;i++) {
                 HttpRequest request = new HttpRequest("http://localhost:8080/pong/say?say=Hello");
                 HttpResponse response = request.executeAsync();
                 if(i==2) {
                     result2 = response.sync().getStatus();
                 }
             }
        expect:
            result2==HttpStatus.HTTP_TOO_MANY_REQUESTS;
    }
    
    @Test
    def "pong server shutdown. ping server send message"() {
        given: "send message"
            PingPongEntity entity = pingComponent.sendPing();
        expect:
            entity.getStatus()==PingPongConstant.STATUS_RESP_OTHER;
    }
    //    @Test
    def "pong server started. ping server send message with lockIndex=1"() {
        given: "set lockIndex"
            pingComponent.setLockIndex(x);
            PingPongEntity entity = pingComponent.sendPing();
        expect:"get result"
            result == entity.getStatus();
        where:"check result"
            x || result
            1 || PingPongConstant.STATUS_RATE_LIMITED
            2 || PingPongConstant.STATUS_RATE_LIMITED
    }
}
